package com.woniuxy.movie.commons.ribbon.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public class WeightRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties ndp;

    @Autowired
    private NacosServiceManager nsm;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    static  class  MyWeightUtil extends Balancer{
        public static Instance getRandomWeight(List<Instance> hosts){
            return Balancer.getHostByRandomWeight(hosts);
        }
    }
    /*
    * 选择实例节点
    * */
    @Override
    public Server choose(Object o) {
        //获取当前请求需要访问的服务ID
        BaseLoadBalancer loadBalancer = (BaseLoadBalancer) getLoadBalancer();
        String name = loadBalancer.getName();
        //获取当前节点的注册信息
        String group = ndp.getGroup();
        String cluster = ndp.getClusterName();
        //获取nacos的服务发现对象
        NamingService ns = nsm.getNamingService(ndp.getNacosProperties());
        //调用服务发现的对象的方法通过上面的参数进行过滤（先查询同组，再看默认组，再看同集群，最后通过权重算法筛选剩下的节点）
        List<Instance> instances = null;
        try {
            instances = ns.selectInstances(name,group,true);
        } catch (NacosException e) {
            try {
                instances = ns.selectInstances(name,"DEFAULT_GROUP",true);
            } catch (NacosException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        List<Instance> clusterInstances = null;
        if (instances!=null&&instances.size()>0) {
            clusterInstances = instances.stream().filter(ins -> ins.getClusterName().equals(cluster)).collect(Collectors.toList());
            if (clusterInstances == null || clusterInstances.size()<=0) {
                clusterInstances = instances;
            }
        }
        //在剩下的节点中通过权重算法选一个
        if (clusterInstances != null && clusterInstances.size()>0) {
            Instance instance = MyWeightUtil.getRandomWeight(clusterInstances);
            //得到服务返回
            return new NacosServer(instance);
        }
        return null;
    }
}
